/**
 *
 */
package cn.hg.jfsa.manage.service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.ehcache.CacheKit;

import cn.hg.jfsa.model.JfsaOrg;

/**
 * @author Golly
 */
public class JfsaOrgService {

	/**
	 * @param org
	 */
	public void del (JfsaOrg org) {
		this.del(org, true);
	}

	/**
	 * @param org
	 * @param withChildren
	 */
	public void del (JfsaOrg org, boolean withChildren) {

		if (withChildren) {
			this.delWithChildren(org);
		} else {
			org.setStatus("del").update();
		}

	}

	/**
	 * @return
	 */
	public List<JfsaOrg> getTree () {
		List<JfsaOrg> tree = CacheKit.get("jfsaOrg", "tree");

		if (null == tree) {
			List<JfsaOrg> list = JfsaOrg.DAO.find("SELECT * FROM jfsa_org WHERE status=?", "on");
			tree = this.buildTree(list, 0);
			tree.add(0, new JfsaOrg().setId(0).setName("-- 顶层 --").setParentId(0).setStatus("on")
				.setType("company").setCreatorId(1).setEditorId(1).setLayerNum(0));
			CacheKit.put("jfsaOrg", "tree", tree);
		}

		return tree;
	}

	/**
	 * @param bean
	 */
	public void updateOrgChildredIds (JfsaOrg bean) {

		if (null == bean) {
			return;
		}

		String childrenIds = Db.queryFirst("SELECT GROUP_CONCAT(id) FROM jfsa_org WHERE status<>'del' AND parent_id=?",
			bean.getId());
		bean.setChildrenIds(childrenIds).update();
	}

	/**
	 * @param list
	 * @param parentId
	 *
	 * @return
	 */
	private List<JfsaOrg> buildTree (final List<JfsaOrg> list, Integer parentId) {
		List<JfsaOrg> tree = new ArrayList<>();

		for (JfsaOrg org : list) {

			if (parentId.equals(org.getParentId())) {
				tree.add(org);
			}

		}

		for (JfsaOrg org : tree) {
			org.setChildren(this.buildTree(list, org.getId()));
		}

		tree.sort(new Comparator<JfsaOrg>() {

			@Override
			public int compare (JfsaOrg o1, JfsaOrg o2) {
				return o1.getSortNum().compareTo(o2.getSortNum());
			}

		});
		return tree;
	}

	/**
	 * @param org
	 */
	private void delWithChildren (JfsaOrg org) {
		org.setStatus("del").update();
		List<JfsaOrg> childrenList = JfsaOrg.DAO.find("SELECT * FROM jfsa_org WHERE status<>'del' AND parent_id = ?",
			org.getId());

		for (JfsaOrg child : childrenList) {
			child.setStatus("del").update();
			this.delWithChildren(child);
		}

	}

}
